// pages/advertiser/index/index.js
var wxCharts = require('../../../utils/wxcharts.js');
const App = getApp();
var lineChart = null;

function getYMDHMS(timestamp) {
  let time = new Date(timestamp)
  let year = time.getFullYear()
  let month = time.getMonth() + 1
  let date = time.getDate()
  let hours = time.getHours()
  let minute = time.getMinutes()
  let second = time.getSeconds()

  if (month < 10) {
    month = '0' + month
  }
  if (date < 10) {
    date = '0' + date
  }
  if (hours < 10) {
    hours = '0' + hours
  }
  if (minute < 10) {
    minute = '0' + minute
  }
  if (second < 10) {
    second = '0' + second
  }
  return month + '-' + date
}

function getDateList() {
  const date = new Date().getTime();
  const arr = []
  let json = {}
  for (let i = 0; i < 7; i++) {
    let d = date - (24 * 60 * 60 * 1000) * i;
    let day = getYMDHMS(d)
    arr.push(day)
  }
  json.values = arr;
  json.className = "column2"
  return json
}

function getbeforeDateList() {
  const date = new Date().getTime();
  const arr = []
  let json = {}
  for (let i = 0; i < 7; i++) {
    let d = date - (24 * 60 * 60 * 1000) * i;
    let day = getYMDHMS(d)
    arr.push(day)
  }
  json.defaultIndex = arr.length -1
  json.values = arr;
  json.className = "column1"
  return json
}


let beforetimeDiy = getbeforeDateList();
let timeDiy = getDateList();

// console.log(beforetimeDiy,1)
// console.log(timeDiy,2)
Page({

  /**
   * 页面的初始数据
   */
  data: {
    dataType: 1,
    tabList: [{
        value: 1,
        text: "曝光量统计"
      },
      // {
      //   value: 2,
      //   text: "投放广告统计"
      // }
    ],
    timeData: "08-26",
    showTime: false,
    // 七天数据
    columnsTime: [
      beforetimeDiy, timeDiy
    ],
    // 初始化
    startTime: beforetimeDiy.values[beforetimeDiy.values.length-1],
    endTime: getYMDHMS(new Date().getTime()),
    showCanvas:true
  },
  // 点击线段
  touchHandler: function (e) {
    // console.log(lineChart.getCurrentDataIndex(e),8);
    lineChart.showToolTip(e, {
      // background: '#7cb5ec',
      format: function (item, category) {
        return category + ' ' + item.name + ':' + item.data
      }
    });
  },
  Oninterval() {
    this.setData({
      showTime: true,
      showCanvas:false
    });
  },
  onClose() {
    this.setData({
      showTime: false,
      showCanvas:true
    });
  },
  formatDate(date) {
    date = new Date(date);
    return `${date.getMonth() + 1}/${date.getDate()}`;
  },
  onConfirm(event) {
    const [start, end] = event.detail;
    this.setData({
      showTime: false,
      timeData: `${this.formatDate(start)} - ${this.formatDate(end)}`,
    });
  },

  addTime() {
    this.setData({
      showTime: true
    })
  },
  cancelTime() {
    this.setData({
      showTime: false
    })
  },
  // 筛选时间，更新线图
  confirmTime(e) {
    // debugger
    this.setData({
      showTime: false
    })
    let value = e.detail.value
    // console.log(time)
    this.setData({
      startTime: `${value[0]}`,
      endTime: `${value[1]}`,
      showCanvas:true
    })
    this.getLineChart()
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {


  },
  makePhoneCall(){
    // 拨打电话
    wx.makePhoneCall({
      phoneNumber: "13377179559"
    })
  },
  /**
   * 点击tab切换
   */
  swichNav: function (e) {
    let _this = this;
    _this.setData({
      dataType: e.target.dataset.current
    }, function () {
      // 获取我的团队列表
      // _this.getTeamList();
    });
  },
  // 跳转
  toJump(e) {
    let url = e.currentTarget.dataset.url;
    wx.navigateTo({
      url: url
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getLineChart()
  },
  //获取统计
  getLineChart() {
    let that = this;
    let categories = []
    let lineData = []
    let year = new Date().getFullYear()
    let _this = this;
    App._get('AdverLog/lineChart', {
      startDate: year + '-' + _this.data.startTime,
      endDate: year + '-' + _this.data.endTime
    }, res => {
      if(res.code ==1){
        res.data.list.map(item => {
          categories.push(item.date.slice(5));
          lineData.push(item.count)
        })
        that.setData(
         {
          categories:categories,
          lineData:lineData,
          daynum:res.data.num
         } 
        )
        // 绘制统计图
        that.drawLine()
        // console.log(categories, lineData)
      }else{
        wx.showToast({
          title: res.data,
          icon:"error"
        })
      }  
    }, false, () => {

    })
  },
  drawLine(){
    let that = this;
    var windowWidth = 0;
    try {
      //创建节点选择器
      var query = wx.createSelectorQuery();
      //选择id
      query.select('.container').boundingClientRect(function (rect) {
        // console.log(rect, 886)
        windowWidth = rect.width;
        lineChart = new wxCharts({
          canvasId: 'lineCanvas',
          type: 'line',
          categories:that.data.categories,
          animation: true,
          // background: '#f5f5f5',
          series: [{
            name: '曝光统计',
            data: that.data.lineData,
            format: function (val, name) {
              // console.log(val,77)
              return val + '次';
            }
          }],
          xAxis: {
            disableGrid: true
          },
          yAxis: {
            // title: '成交金额 (万元)',
            // format: function (val) {
            //     return val.toFixed(2);
            // },
            // min: 0
          },
          width: windowWidth,
          height: 200,
          dataLabel: false,
          dataPointShape: true,
          extra: {
            lineStyle: 'curve'
          }
        });
      }).exec();
    } catch (e) {
      console.error('getSystemInfoSync failed!');
    }
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})